#!/usr/bin/env node

/*
example:
#!/usr/bin/env iojs

console.log("pre");
var a = $`echo -n fangyunjiang`;
console.log("from shell:", a);
console.log('post')

var a = $`cat index.js|grep registerGlobals`.pipe($$`wc -l`)
if (a.error) {
    console.log("error: ", a.msg);
} else {
    console.log('output: ', a);
}
*/

const url = require('url');
require('./js/zx.js');
const file = process.argv[2];

if (!fs.existsSync(file)) {
    console.error('script file is not exists');
    process.exit(0);
}
let _filename = path.resolve(file);
let _dirname = path.dirname(_filename);

const tempFile = path.join(path.dirname(file), `.__temp__${path.basename(file)}__.js`);
let content = fs.readFileSync(file, 'utf-8').split(/\n/).slice(1).join('\n');
content = content.replace(/(\$`)/g, 'await $1').replace(/\$await (\$`)/g, '$1');
fs.writeFileSync(tempFile, `(async()=>{${content}})()`, 'utf-8');
Object.assign(global, { __filename: _filename, __dirname: _dirname });
require(url.pathToFileURL(tempFile).pathname);
fs.unlinkSync(tempFile);
